<?php
class ServerController extends Controller{

	public function actionApi(){
		//dbg($_SERVER['PHP_AUTH_USER']);
		if(!isset($_SERVER['PHP_AUTH_USER'])){
			header("WWW-Authenticate:Basic realm");dbg('dsf');
			header("HTTP/1.0 401 Unauthorized");
			echo 'username required!';
			exit;
		}
		$Account = new AccountForm();
		$Account->email = $_SERVER['PHP_AUTH_USER'];
		$Account->password = md5($_SERVER['PHP_AUTH_PW']);
		//dbg($Account);
		//dbg(!$Account->login());
		if($Account->login()){
			if(isset($_GET['statuses'])){
				$criteria = new CDbCriteria(array(
					'order'=>'update_time DESC',
					'limit'=>6,
				));
				$myUpper = Upper::getUpper(Yii::app()->user->id,'self');
				foreach($myUpper as $val){
					$upperIds[] = $val->user_id;
				}
				//dbg(Yii::app()->user->id);
				$criteria->addInCondition("t.user_id",$upperIds,'');
				$upperNews = News::model()->findAll($criteria);
			
				$jsonNews = "[";
				if(count($upperNews)){
					foreach($upperNews as $value){
						//dbg($value->attributes['user_name'],true);
						//$arr['create_at']
						date_default_timezone_set("PRC");
						$jsonNews.=json_encode(array(
							'created_at'=>date('D M j H:i:s O Y',$value->attributes['post_time']),
							'id'=>$value->attributes['news_id'],
							'text'=>"【<a href='http://".$_SERVER['HTTP_HOST']."/news/".$value->attributes['news_id']."'>".$value->attributes['site_title']."</a>】".$value->attributes['news_desc'],
							'picPath'=>'[]',
							'source'=>'网站',
							'in_reply_to_status_id'=>'',
							'in_reply_to_user_id'=>'',
							'in_reply_to_user_name'=>'',
							'favorited'=>'false',
							'in_reply_to_screen_name'=>'',
							'user'=>array(
								'id'=>$value->attributes['user_id'],
								'name'=>$value->attributes['user_name'],
								'screen_name'=>$value->attributes['user_name'],
								'profile_image_url'=>NC::getUserIcon($value->attributes['user_id']),
								'url'=>"http://".$_SERVER['HTTP_HOST']."/upper/".$value->attributes['user_id'],
								),
						)
						);
						
						$jsonNews.=',';
					}
					$jsonNews = substr($jsonNews,0,-1);
				}
				$jsonNews.="]";
				//echo 'asdf';
				//dbg($jsonNews);
				//dbg($upperNews[0]->attributes);
				header("Content-type: application/json; charset=UTF-8");
				echo $jsonNews;
			}
			if(isset($_GET['messages'])){
				$link_url = isset($_POST['text']) ? $_POST['text']: isset($_GET['text'])?$_GET['text']:null;
				$link_title = isset($_REQUEST['title'])?trim($_REQUEST['title']):null;
				if($link_url){
					$validateUrlUnique = News::validateUrlUnique($link_url);
					if($validateUrlUnique !== null){
						echo json_encode(array(
							'info'=>'该网址已被人添加过了!',
						));
						exit;
					}else{
						$model = new News('server');
						$curl = new Curl();
						$crawl = $curl->getData($link_url);
						if($crawl['success']){
							$tag = NC::splitword($crawl['keyword'],$crawl['description']);
							$news_tag = "";
							if(count($tag)){
								foreach($tag as $val){
									$news_tag .= $val." ";
								}
							}
							$model->news_tag = $news_tag;
							$model->comment_num = 0;
							$model->news_desc = $crawl['description'];
							if($link_title){
								$model->site_title = $link_title;
							}elseif($crawl['title']){
								$model->site_title = $crawl['title'];
							}else{
								$model->site_title = '暂无标题';
							}
							//$model->site_title = $link_title?$link_title:$crawl['title']?$crawl['title']:'暂无标题';
							$model->link_url = $link_url;
							$model->digg_num = 1;
							$model->trash_num = 0;
							$model->comment_num = 0;
							$model->user_id = Yii::app()->user->id;
							$model->user_name = $_SERVER['PHP_AUTH_USER'];
						}
						
						if($model->createNews($model)){
							$news_id = $model->primaryKey;
							//写入到一个文件中，让其去自动抓取默认照片
							CacheFile::cacheThumb($news_id,$model->link_url);
							echo json_encode(array(
								'id'=>$news_id,
								'info'=>"发送成功",
							));
						}else{
							echo json_encode(array(
								'info'=>"发送失败",
							));exit;
						}
					}
				}else{
					echo json_encode(array(
						'info'=>"请求失败",
					));exit;
				}
			}
		}else{
			header("WWW-Authenticate:Basic realm");
			header("HTTP/1.0 401 Unauthorized");
			exit();
		}
	}
	public function getNews(){
		$upper = Upper::getUpper(Yii::app()->user->id,'self');
		return $upper;
	}
	public function actionAddNews(){
		require_once('../lib/soap/nusoap.php');
		$server = new soap_server();
		// Initialize WSDL support
		$server->configureWSDL('newswsdl', 'urn:/newswsdl');
		$server->soap_defencoding='utf-8';
		// Register the method to expose
		$server->register('addNews',                // method name
			array('link' => 'xsd:string','title' => 'xsd:string','desc'=>'xsd:string'),        // input parameters
			array('return' => 'xsd:string'),      // output parameters
			'urn:newswsdl',                      // namespace
			'urn:newswsdl#addNews',                // soapaction
			'rpc',                                // style
			'encoded',                            // use
			'add news information'            // documentation
		);
		// Define the method as a PHP function
		function addNews($link,$title,$desc){
			//return $title;
			return json_encode(array('link'=>$link,'title'=>$title,'desc'=>$desc));
		}
		// Use the request to (try to) invoke the service
		$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
		$server->service($HTTP_RAW_POST_DATA);
	}
	public function addNews($uid,$uname){
		//return json_encode(array('link'=>$link,'title'=>$title,'desc'=>$desc));
		return $link;
	}

	
}
?>